package cn.hfjava.kz.service.impl;

import cn.hfjava.kz.controller.OcrController;
import cn.hfjava.kz.controller.UploadController;
import cn.hfjava.kz.entity.dto.StudentQueryDTO;
import cn.hfjava.kz.entity.dto.StudentSavaDTO;
import cn.hfjava.kz.entity.dto.StudentSearchDTO;
import cn.hfjava.kz.entity.excel.StudentExcel;
import cn.hfjava.kz.entity.po.Document;
import cn.hfjava.kz.entity.po.Student;
import cn.hfjava.kz.entity.vo.PageVO;
import cn.hfjava.kz.entity.vo.StudentVO;
import cn.hfjava.kz.exception.BizException;
import cn.hfjava.kz.mapper.DocumentMapper;
import cn.hfjava.kz.mapper.StudentMapper;
import cn.hfjava.kz.service.DocumentService;
import cn.hfjava.kz.service.StudentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import org.springframework.web.multipart.MultipartFile;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
* @author 86177
* @description 针对表【students(考生表)】的数据库操作Service实现
* @createDate 2024-07-10 09:24:13
*/
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
    implements StudentService{
    @Resource
    private StudentMapper studentMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private UploadController uploadController;

    @Autowired
    private OcrController ocrController;

    @Autowired
    private DocumentMapper documentMapper;
    @Override
    public PageVO<StudentVO> findByPage(StudentQueryDTO studentQueryDTO) {
        PageHelper.startPage(studentQueryDTO.getCurPage(), studentQueryDTO.getPageSize());
        List<StudentVO> studentVoList = studentMapper.getStudentVoList(studentQueryDTO);
        long total = studentMapper.getStudentVoCount(studentQueryDTO);
        PageVO pageVO = new PageVO<>(studentQueryDTO.getCurPage(),studentQueryDTO.getPageSize(),total,studentVoList);
        return pageVO;
    }
    @Override
    public void addData(List<StudentExcel> list, String createdBy, Integer userId) {
        List<Student> studentsToSave = new ArrayList<>();
        for (StudentExcel excelStudent : list) {
            Student student = new Student();

            // 设置从Excel导入的字段
            student.setName(excelStudent.getName());
            student.setIdentityId(excelStudent.getIdentity());
            student.setPhone(excelStudent.getPhone());
            student.setEducation(excelStudent.getEducation());
            student.setNation(excelStudent.getNation());
            student.setSource(excelStudent.getSource());
            student.setAddress(excelStudent.getAddress());
            student.setWorkAge(excelStudent.getWorkAge());
            student.setWorkUnit(excelStudent.getWorkUnit());
            student.setRemark(excelStudent.getRemark());

            // 设置从控制器获取的字段
            student.setCreatedBy(createdBy);
            student.setUserId(userId);
            student.setNongYe(excelStudent.getNongYe());

            // 生成一个默认或随机的密码，并加密
            String defaultPassword = "123456"; // 或者使用随机生成的密码
            String passwordHash = bCryptPasswordEncoder.encode(defaultPassword);
            student.setPassword(passwordHash);

            studentsToSave.add(student);
        }

        // 批量插入数据到数据库
        studentMapper.batchInsert(studentsToSave);
    }




    @Override
    public List<StudentExcel> getData() {
        return studentMapper.getData();
    }



    @Override

    public List<StudentExcel> findStudentExcelByIdList(List<Integer> idList) {
        // 查询数据库获取考生信息
        return studentMapper.findStudentExcelByIdList(idList);
    }


    @Override
    // 检测重复数据的方法
    public boolean checkForDuplicates(List<StudentExcel> students) {

        for (StudentExcel student : students) {
            // 获取当前考生的身份证号码
            String identity = student.getIdentity();
            // 根据当前考生的身份证号码在数据库中查找是否存在其他考生
            List<StudentExcel> existingStudents = studentMapper.findStudentExcelByIdentity(identity);
            // 如果存在其他考生，则返回true，表示有重复数据
            if (!existingStudents.isEmpty()) {
                return true;
            }
        }

        return false; // 仅为示例，需根据实际实现来确定
    }


    @Override
    public PageVO<Student> searchPage(StudentSearchDTO dto) {
        if (Objects.isNull(dto)) {
            throw new BizException(500, "查询条件对象为null");
        }

        // 过滤空字符串，将它们设置为null
        if (StringUtils.isEmpty(dto.getName())) {
            dto.setName(null);
        }
        if (StringUtils.isEmpty(dto.getIdNum())) {
            dto.setIdNum(null);
        }
        if (StringUtils.isEmpty(dto.getTeacher())) {
            dto.setTeacher(null);
        }
        if (StringUtils.isEmpty(dto.getSource())) {
            dto.setSource(null);
        }
        if (StringUtils.isEmpty(dto.getPhone())) {
            dto.setPhone(null);
        }

        LambdaQueryWrapper<Student> queryCondition = new LambdaQueryWrapper<>();
        queryCondition.like(StringUtils.hasLength(dto.getName()), Student::getName, dto.getName());
        queryCondition.like(StringUtils.hasLength(dto.getIdNum()), Student::getIdentityId, dto.getIdNum());
        queryCondition.like(StringUtils.hasLength(dto.getTeacher()), Student::getTeacher, dto.getTeacher());
        queryCondition.eq(dto.getStatus() != null && dto.getStatus() != -1, Student::getStatus, dto.getStatus());

        if (dto.getStartTime() != null) {
            queryCondition.apply("date_format(createdDate,'%Y-%m-%d') >= {0}", dto.getStartTime());
        }

        if (dto.getEndTime() != null) {
            queryCondition.apply("date_format(createdDate,'%Y-%m-%d') <= {0}", dto.getEndTime());
        }

        IPage<Student> page = new Page<>(dto.getCurPage(), dto.getPageSize());
        queryCondition.select(Student.class, info ->
                !info.getColumn().equals("deleted")
                        && !info.getColumn().equals("userId")
                        && !info.getColumn().equals("password"));

        IPage<Student> pageResult = studentMapper.selectPage(page, queryCondition);

        PageVO<Student> pageVO = new PageVO<>();
        pageVO.setCurrentPage(pageResult.getCurrent());
        pageVO.setPageSize(pageResult.getSize());
        pageVO.setTotal(pageResult.getTotal());
        pageVO.setList(pageResult.getRecords());
        return pageVO;
    }


    @Override
    public void saveStuAllInfo(StudentSavaDTO studentPo, String name, int userId) {
        Student student = new Student();

        student.setName(studentPo.getName());
        student.setPassword(studentPo.getPassword());
        student.setIdentityId(studentPo.getIdNum());
        if(studentPo.getAvatar()==null){
            student.setAvatar("https://img2.baidu.com/it/u=1661624596,544958493&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1709139600&t=8bd455a8d9fa53929c892bc3d0ba556d");
        }
        student.setNation(studentPo.getNation());
        student.setEducation(studentPo.getEducation());
        student.setSource(studentPo.getSource());
        if(Objects.equals(studentPo.getNongYe(), "是")){
            student.setNongYe(1);
        }else{
            student.setNongYe(0);
        }
        student.setPhone(studentPo.getPhone());
        student.setWorkAge(studentPo.getWorkAge());
        student.setAddress(studentPo.getAddress());
        student.setTeacher(studentPo.getTeacher());
        student.setWorkUnit(studentPo.getWorkUnit());
        student.setCreatedBy(name);
        student.setUserId(userId);
        student.setStatus(0);
        student.setDeleted(0);
        student.setRemark(studentPo.getRemark());
        studentMapper.insert(student);
        //返回此时的考生id,通过身份证号
        Integer id = studentMapper.selectIdByIdNum(studentPo.getIdNum());
        if(studentPo.getInsurance()!=null){
            Document doc1 = new Document();
            doc1.setDocUrl(studentPo.getInsurance());
            doc1.setTitle(studentPo.getPhone()+"_参保证明");
            doc1.setCreatedUser(name);
            doc1.setStudentId(id);
            doc1.setUserId(userId);
            documentMapper.insert(doc1);
        }

        if(studentPo.getPhoto()!=null){
            Document doc2 = new Document();
            doc2.setDocUrl(studentPo.getPhoto());
            doc2.setTitle(studentPo.getPhone()+"_个人相片");
            doc2.setCreatedUser(name);
            doc2.setStudentId(id);
            doc2.setUserId(userId);
            documentMapper.insert(doc2);
        }
        if(studentPo.getCertNo()!=null){
            Document doc3 = new Document();
            doc3.setDocUrl(studentPo.getCertNo());
            doc3.setTitle(studentPo.getPhone()+"_毕业证书");
            doc3.setCreatedUser(name);
            doc3.setStudentId(id);
            doc3.setUserId(userId);
            documentMapper.insert(doc3);
        }
        if(studentPo.getIdCardFront()!=null){
            Document doc4 = new Document();
            doc4.setDocUrl(studentPo.getIdCardFront());
            doc4.setTitle(studentPo.getPhone()+"_身份证正面");
            doc4.setCreatedUser(name);
            doc4.setStudentId(id);
            doc4.setUserId(userId);
            documentMapper.insert(doc4);
        }
        if(studentPo.getIdCardBack()!=null){
            Document doc5 = new Document();
            doc5.setDocUrl(studentPo.getIdCardBack());
            doc5.setTitle(studentPo.getPhone()+"_身份证反面");
            doc5.setCreatedUser(name);
            doc5.setStudentId(id);
            doc5.setUserId(userId);
            documentMapper.insert(doc5);
        }
    }
}

